function [ EC, tictoctime ] = APEmat2asc( filename, outtype, processed) 
%[ EC, tictoctime ] = APEmat2asc( filename, outtype, processed) 
% 
% APEmat2asc converts APE MAT files to comma seperated value (CSV), tab 
% seperated value (TSV), space seperated value (SSV) or even Excel type 
% (xls) files.
% Converted files will be saved in the same folder as the source.
%
%  !!!! ATTENTION: if files are already present they will be overwriten
%                  without warning !!!!
%
% INPUT     filename    :   name of file to convert with full path. MUST be
%                           in APE MAT format (i.e. produced with the 
%                           SLS APE toolkit). Use [0] to batch full folder.
%           outtype     :   sets the type of file to convert to. 
%                           1 or 'csv' =  comma seperated value (*.csv)
%                          [2]or 'tsv' =  TAB seperated value (*.asc)
%                           3 or 'ssv' =  SPACE seperated value (*.ssv)
%                           4 or 'xls' =  Excel file (*.xls)
%                             --> DEFAULT is 'csv'
%           processed   :  [0] = export RAW data
%                           1  = export Raman corrected data
%                                (ramandatax & ALSdatay)
%
% OUTPUT    EC          :   Error Code. (0 = success, 1 = error)
%           tictoctime  :   time in second to perform conversion

%  (c) F. Dworkowski, 2011
%      Version 1.3, 2012-04-12

tic

if nargin < 1
    help APEmat2asc
    return
elseif nargin < 2
    outtype = 2;
    processed = 0;
elseif nargin <3
    processed = 0;    
end

% Load the file

if filename == 0
    batchYN = 1;
    [FileName,PathName,FilterIndex] = uigetfile({'*.mat';'*.*'});
    if isequal(PathName,0)
       disp('User selected Cancel')
       EC = 1;
       return
    else
       % disp(['User selected ', fullfile(PathName)])
       disp(['User selected ', fullfile(PathName, FileName)])
    end
    
    cd(PathName)
    if FilterIndex == 2
        filelist=dir('*.*');        % Detect all available files
    else
        filelist=dir('*.mat');      % Detect all available .mat files
    end
    loopIdx = length(filelist);
else
    batchYN =0;
    loopIdx =1;
end

while loopIdx >= 1
    if batchYN == 1
        [pathstr, filename, ext] = fileparts(filelist(loopIdx).name);
    end
    try load(filename)
    catch ME
      errordlg('ERROR: file not found in "APEmat2asc"!')
      EC = 1;
      return
    end

    % Check if output type was chosen and correct to csv if something wrong
    if nargin == 1
        outtype = 'csv';
    elseif nargin == 2
        if ~isnumeric(outtype)
            switch outtype
                case 'csv'
                    outtype = 1;
                case 'tsv'
                    outtype = 2;
                case 'ssv'
                    outtype = 3;
                case 'xls'
                    outtype = 4;
                otherwise
                    errordlg({'ERROR: type of output file was chosen incorrectly' ...
                                'Will assume csv-type was desired.' ...
                                'For other filetypes please see the help'});
                    outtype = 1;
                    EC = 1;
            end
        end
        if (outtype ~= [1 2 3 4])
            errordlg({'ERROR: type of output file was chosen incorrectly' ...
                        'Will assume csv-type was desired.' ...
                        'For other filetypes please see the help'});
            outtype = 1;
            EC = 1;
        end
    end

    switch processed
        case 0
            % Calculate size of output matrix
            lengthx=length(datax);
            [lengthy, numberofspectra]=size(datay);
            % ----- Generate output matrix -----
            outdata = zeros((numberofspectra+1), lengthx);
            outdata = [datax datay];
        case 1
            if exist('ramandatax','var')==0
                 errordlg({'ERROR: Processed Raman data' ...
                'not present.'});
                EC = 1;
                return
            end
            lengthx = length(ramandatax);
            [lengthy, numberofspectra]=size(ALSdatay);
            % ----- Generate output matrix -----
            outdata = zeros((numberofspectra+1), lengthx);
            outdata = [ramandatax ALSdatay];

        otherwise
            errordlg({'ERROR: Type of data to export' ...
                'was not declared.'});
            EC = 1;
    end

    % Generate output file and perform save
    [pathstr, name, ext] = fileparts(filename);
    % make sure to save to the atarting path, not nececarrily th data path
    pathstr = '';

    switch outtype
        case 1                          % 'csv'
            fileout = fullfile(pathstr,[name,'.csv']);
            csvwrite(fileout,outdata)
            EC = 0;
        case 2                          % 'tsv'
            fileout = fullfile(pathstr,[name,'.asc']);
            dlmwrite(fileout, outdata, 'delimiter', '\t', 'precision', 6)
            EC = 0;
        case 3                          % 'ssv'
            fileout = fullfile(pathstr,[name,'.ssv']);
            dlmwrite(fileout, outdata, 'delimiter', ' ', 'precision', '%6g%')
            EC = 0;
        case 4                          % 'xls'
            fileout = fullfile(pathstr,[name,'.xls']);
            [xlsrc, xlsmsg] = xlswrite(fileout, outdata);
            switch xlsrc
                case 1
                    EC = 0;
                case 2
                    errordlg('Failed to write XLS. Maybe datafile to large?');
                    EC = 1;
                    return
            end
    end
    loopIdx = loopIdx-1;
end
tictoctime=toc;

end
